package com.lzx.hbh_system.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JWTUtil {
    // 过期时间5分钟
    private static final long EXPIRE_TIME = 5*60*1000;
    private static final long EXPIRE_TIME_test = 10*1000;//10秒
    /**
     * 校验token是否正确
     * @param token 密钥
     * @param secret         //使用salt+MD5加密’用户名‘后的密文再取MD5的值作为secret生成token
     * @return 是否正确
     */
    public static boolean verify(String token, String username, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     * @param username 用户名
     * @param secret         //使用salt+MD5加密’用户名‘后的密文再取MD5的值作为secret生成token
     * @return 加密的token
     */
    public static String sign(String username, String secret) {
        try {
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带username信息
            return JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
    public static String sign2(String username, String secret) {
        try {
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME_test);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带username信息
            return JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
    /** --实用性待定
     * 判断token是否过期
     * true 过期
     * false 还没过期
     *
     */
    public static Boolean isTokenExpired(String token,Long accessTokenTimeMils){
        if(StringUtils.isEmpty(token)) {
            return false;
        }
        try {
            Long nowtime = new Date().getTime();//当前时间戳
            Long exptime = nowtime - EXPIRE_TIME_test - accessTokenTimeMils;
            if(exptime < 2 ){
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * test
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
//        String test_token = sign2("1","1");
//        Long actime = new Date().getTime();
//        Thread.sleep(10000);
//        System.out.println(isTokenExpired(test_token, actime));
        /*System.out.println(verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDMyNjg2MjgsInVzZXJuYW1lIjoiMSJ9.KgRxN7uyM_FQB2sNqMs7hQd5J3seTj9vOQuRYWoIp_o","1","F8DB9CCBE36DAA711DE12A746726DB57"));
        System.out.println(getUsername("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDMyNjMzMTksInVzZXJuYW1lIjoiMSJ9.X1GIs8vhDmvFxsY9rtdNeE-dQ84xgqfD9ss4V_2ckKc"));*/
        String secret = Md5Utils.MD5("0rd%m"+"admin");
        System.out.println("生成的新的secret："+secret);
        //生成新token
        String newToken = JWTUtil.sign("admin",secret);
        System.out.println(newToken);
    }
}
